import axios from 'axios';
import qs from 'qs';
import { message } from 'antd';
import Cookies from 'js-cookie';

import { store } from '@/store';
import { setLoginOpen, setUserInfo } from '@/reducers/main';
import { LOGIN, VALIDATE } from '@/config/url';
import i18next from 'i18next';  // 导入 i18next
import { Modal } from 'antd';

const abortController = new AbortController();
const { signal } = abortController;
/*
    错误提示，不在这里添加，原因就是很多时候都是好多请求并发请求的，如果在这里提示，那么就会出现一种情况，一下出现很多错误提示
*/
export default function request(url, options = {}) {
    let isUrlEncoded = options.contentType === 'application/x-www-form-urlencoded',
        isFormData = options.contentType === 'multipart/form-data',
        requestUrl = url,
        responseBlob = options.responseType === 'blob',
        Authorization = { token: Cookies.get('portal_token') },
        language = localStorage.getItem('portal_language') || 'en-US',
        progressObj = {};

    // 对于 GET/DELETE 请求，或者是特定 POST 请求并且需要 URL 参数
    if ((!options.method || (['GET', 'DELETE'].includes(options.method?.toUpperCase()))) && options.data && Object.keys(options.data).length) {
        requestUrl += `?${qs.stringify(options.data || {})}`;
    }

    // 对于 POST 请求且使用 URL 参数的情况，将参数拼接到 URL 上
    if (options.method?.toUpperCase() === 'POST' && options.isUrlParam && options.urlParams && Object.keys(options.urlParams).length) {
        requestUrl += `?${qs.stringify(options.urlParams)}`;
    }
    if (options.onUploadProgress && 'function' === typeof (options.onUploadProgress)) {
        progressObj['onUploadProgress'] = options.onUploadProgress;
    }

    let ajaxOption = {
        url: requestUrl,
        method: options.method || 'GET', // 默认 get
        baseURL: ``, // baseURL 将自动加在 `url` 前面，除非 `url` 是一个绝对 URL。
        headers: {
            'Content-Type': options.contentType || 'application/json',
            ...Authorization,
            'Accept-Language': language
        },
        data: options.isUrlParam ? undefined : (isUrlEncoded ? qs.stringify(options.data || {}) : (isFormData ? options.data : JSON.stringify(options.data || {}))),
        timeout: options.timeout || 60000, // 超时时间 60秒
        responseType: options.responseType || 'json', // 表示服务器响应的数据类型
        ...progressObj,
    };

    return new Promise((resolve, reject) => {
        axios(ajaxOption).then(response => {
            if (200 === response?.status) {
                if (responseBlob) {
                    return resolve(response?.data || null); // Resolve Blob data
                } else {
                    if (response?.data?.code === 0 || response?.data?.code === '0') {
                        resolve(response?.data || null);
                        store.dispatch(setLoginOpen(false));
                    } else if ((response?.data?.code === -3001 || response?.data?.code === -3002) && VALIDATE !== url) {
                        Cookies.remove('portal_token');
                        store.dispatch(setUserInfo({}));
                        localStorage.removeItem("portal_userinfo");
                        Modal.confirm({
                            title: i18next.t('login.text.expired.title'),
                            content: i18next.t('login.text.expired.content'),
                            okText: i18next.t('login.loginBtn'),
                            cancelText: i18next.t('common.modal.button.cancel'),
                            onOk() {
                                window.location.href = '/login';
                             },
                            onCancel() {
                            },
                            okButtonProps: {
                                className: 'custom-ok-button',
                            },
                            cancelButtonProps: {
                                className: 'custom-cancel-button',
                            },
                        });
                        // return reject({ code: 401, msg: i18next.t('common.httperror.Unauthorized'), data: null });
                    } else {
                        resolve({
                            code: response?.data?.code,
                            message: response?.data?.message || '',
                            data: response?.data || null
                        });
                    }
                }
            } else {
                reject({
                    code: response?.status || 500,
                    data: null,
                    message: i18next.t('common.httperror.abnormality')
                });
            }
        }).catch(error => {
            reject({ code: 500, data: null, message: i18next.t('common.httperror.Connection') });
        });
    });
}
